/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "tim.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
int positive_float_to_string(float num, char *str, int int_len, int dec_len);
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */
  
  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM3_Init();
  MX_I2C1_Init();
  /* USER CODE BEGIN 2 */

  // 初始化OLED
  OLED_Init();
  OLED_Clear();
  // OLED_DisplayMode(0xa7);
  int num = 0;
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    // 让计数器归零
    __HAL_TIM_SET_COUNTER(&htim3,0);

    // 清除CCx标志位
    __HAL_TIM_CLEAR_FLAG(&htim3,TIM_FLAG_CC1);
    __HAL_TIM_CLEAR_FLAG(&htim3,TIM_FLAG_CC2);

    // IC(Input Capture)
    // 启动输入捕获
    HAL_TIM_IC_Start(&htim3,TIM_CHANNEL_1);
    HAL_TIM_IC_Start(&htim3,TIM_CHANNEL_2);

    // 向Triggle发送超过1us的脉冲
    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_0,GPIO_PIN_SET);
    HAL_Delay(1);
    HAL_GPIO_WritePin(GPIOE,GPIO_PIN_0,GPIO_PIN_RESET);

    // 等待测量结束
    uint8_t success = 0;
    uint32_t expireTime =  HAL_GetTick()+50;
    while(HAL_GetTick() <= expireTime)
    {
      uint32_t cc1Flag = __HAL_TIM_GET_FLAG(&htim3,TIM_FLAG_CC1);
      uint32_t cc2Flag = __HAL_TIM_GET_FLAG(&htim3,TIM_FLAG_CC2);
      if(cc1Flag != 0 && cc2Flag != 0){
        success = 1;
        break;
      }
    }

    // 关闭输入捕获
    HAL_TIM_IC_Stop(&htim3,TIM_CHANNEL_1);
    HAL_TIM_IC_Stop(&htim3,TIM_CHANNEL_2);
    
    // 计算结果
    uint32_t ccr1 = __HAL_TIM_GET_COMPARE(&htim3,TIM_CHANNEL_1);
    uint32_t ccr2 = __HAL_TIM_GET_COMPARE(&htim3,TIM_CHANNEL_2);
    float pulseWidth = (ccr2 - ccr1) * 1e-6;
    float distance = 340 * pulseWidth / 2;
    distance *= 100;
    // oled显示距离
    OLED_ShowString(0,1,"distance:",8,0);
    char str[50];
    sprintf(str,"%.2f",distance);
    int xlen = sizeof(str)/sizeof(str[0]);
    OLED_ShowString(0,3,str,sizeof(str)/sizeof(str[0]),0);
    OLED_ShowString(xlen,3,"cm",2,0);
    // num++;
    // sprintf(str,"%d",num);
    // OLED_ShowString(0,3,str,sizeof(str)/sizeof(str[0]),0);
    if(distance < 3)
    {
      HAL_GPIO_WritePin(GPIOE,GPIO_PIN_1,GPIO_PIN_RESET);
    }else{
      HAL_GPIO_WritePin(GPIOE,GPIO_PIN_1,GPIO_PIN_SET);
    }
    HAL_Delay(0.1);

    
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
/**
 * @brief 将正数float类型转换为字符串
 * @param num 要转换的正浮点数（若输入负数会按绝对值处理）
 * @param str 存储结果的字符数组
 * @param int_len 整数部分最小长度(不足补空格，0表示不补)
 * @param dec_len 小数部分长度(0表示不保留小数)
 * @return 转换后的字符串长度，失败返回-1
 */
int positive_float_to_string(float num, char *str, int int_len, int dec_len) {
    // 检查参数合法性
    if (str == NULL || dec_len < 0 || int_len < 0) {
        return -1;
    }
    
    // 确保处理的是正数（取绝对值）
    if (num < 0) {
        num = -num;
    }
    
    // 四舍五入处理，避免精度问题
    if (dec_len > 0) {
        float round_factor = pow(10, dec_len);
        num = round(num * round_factor) / round_factor;
    }
    
    // 分离整数和小数部分
    long long integer_part = (long long)num;
    float decimal_part = num - integer_part;
    
    // 转换整数部分为字符串
    char int_str[20];
    sprintf(int_str, "%lld", integer_part);
    int actual_int_len = strlen(int_str);
    
    // 计算总长度
    int total_len = (int_len > actual_int_len) ? int_len : actual_int_len;  // 整数部分
    total_len += (dec_len > 0) ? (1 + dec_len) : 0;  // 小数点和小数部分
    total_len += 1;  // 结束符'\0'
    
    // 转换小数部分为字符串
    char dec_str[20] = {0};
    if (dec_len > 0) {
        long long dec_val = (long long)(decimal_part * pow(10, dec_len) + 0.5);
        sprintf(dec_str, "%0*lld", dec_len, dec_val);
    }
    
    // 组合结果
    int idx = 0;
    
    // 整数部分补空格(如果需要)
    int space_count = (int_len > actual_int_len) ? (int_len - actual_int_len) : 0;
    for (int i = 0; i < space_count; i++) {
        str[idx++] = ' ';
    }
    
    // 复制整数部分
    strcat(&str[idx], int_str);
    idx += actual_int_len;
    
    // 复制小数部分
    if (dec_len > 0) {
        str[idx++] = '.';
        strcat(&str[idx], dec_str);
        idx += dec_len;
    }
    
    // 添加结束符
    str[idx] = '\0';
    
    return total_len - 1;  // 不包含结束符的长度
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
